package com.weijx.dishes.controller;

import com.weijx.dishes.config.FrontendConfig;
import com.weijx.dishes.utils.ReturnResult;
import com.weijx.dishes.entity.Order;
import com.weijx.dishes.service.OrderService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * com.weijx.dishes.controller.OrderController
 * 描述：
 * on 2025/10/24-下午4:00
 *
 * @author weijx
 */


@RestController
@RequestMapping("/api/orders")
public class OrderController {

    @Resource
    private OrderService orderService;

    @Resource
    private FrontendConfig frontendConfig;

    /**
     * 创建订单
     */
    @PostMapping
    public ReturnResult<Map<String, String>> createOrder(
            @RequestBody Order order,
            @CookieValue(value = "user_openid", required = false) String customerOpenId) {
        try {
            // 安全校验：确保用户是从公众号菜单进入的
            if (customerOpenId == null || customerOpenId.isEmpty()) {
                return ReturnResult.error(401, "无法获取用户信息，请从公众号菜单进入点餐。", null);
            }
            // 校验：确保前端传递了处理人ID
            if (order.getHandlerOpenId() == null || order.getHandlerOpenId().isEmpty()) {
                return ReturnResult.error(400, "请指定一个订单处理人。", null);
            }

            // 将从Cookie中获取的下单人ID设置到订单对象中
            order.setCustomerOpenId(customerOpenId);

            String orderId = orderService.createOrder(order);
            Map<String, String> result = new HashMap<>();
            result.put("orderId", orderId);
            result.put("message", "订单提交成功，我们会尽快处理！");
            return ReturnResult.success("订单创建成功", result);
        } catch (Exception e) {
            return ReturnResult.error(500, "订单创建失败: " + e.getMessage(), null);
        }
    }

    /**
     * 根据ID获取订单详情
     */
    @GetMapping("/{id}")
    public ReturnResult<Order> getOrderById(@PathVariable String id) {
        try {
            Order order = orderService.getOrderById(id);
            if (order != null) {
                return ReturnResult.success("获取订单成功", order);
            } else {
                return ReturnResult.error(404, "订单不存在", null);
            }
        } catch (Exception e) {
            return ReturnResult.error(500, "获取订单失败: " + e.getMessage(), null);
        }
    }

    /**
     * 处理订单（完成或驳回）
     */
    @PutMapping("/{id}/process")
    public ReturnResult<String> processOrder(
            @PathVariable String id,
            @RequestBody Map<String, Object> processData) {
        try {
            Integer orderStatus = (Integer) processData.get("orderStatus");
            String processNote = (String) processData.get("processNote");

            boolean success = orderService.processOrder(id, orderStatus, processNote);
            if (success) {
                String message = orderStatus == 1 ? "订单已完成" : "订单已驳回";
                return ReturnResult.success(message, null);
            } else {
                return ReturnResult.error(500, "订单处理失败", null);
            }
        } catch (Exception e) {
            return ReturnResult.error(500, "订单处理失败: " + e.getMessage(), null);
        }
    }

    /**
     * 订单处理页面重定向（邮件中的链接）
     * 现在重定向到Thymeleaf页面，不再需要跨域
     */
    @GetMapping("/process/{id}")
    public String orderProcessPage(@PathVariable String id) {
        return "redirect:/process?orderId=" + id;
    }
}
